use std::collections::HashMap;

fn main() {
    println!("Hello, world!");
    let s1 = String::from("hi ");
    let s2 = String::from("world");
    let mut s3 = s1 + &s2;
    s3.push_str(" aa");
    println!("s1: 不行了, s2: {}, s3:{}", s2, s3);

    let mut md = HashMap::new();
    md.insert("name", "zhangsan");
    md.insert("age", "18");
    println!("{:?}", md);
    md.insert("name", "lisi");
    println!("{:?}", md);
    md.insert("name", "wangwu");
    println!("{:?}", md);
    md.entry("age").or_insert("28");
    println!("{:?}", md);
    md.remove(&"age");
    println!("{:?}", md);

    // 练习问题：
    //
    // 给定一组整数，使用 vector 并返回这个列表的中位数（排列数组后位于中间的值）和众数（出现次数最多的值；在这里哈希 map 会很有帮助）。
    let mut numbers = vec![34, 50, 25, 100, 90];
    let (median, mode) = calculate_stats(&mut numbers);
    println!("median: {}, mode: {}", median, mode);
    // 将字符串转换为 pig latin。也就是每一个单词的第一个辅音字母被移动到单词的结尾并增加 ay，所以 first 会变成 irst-fay。元音字母开头的单词则在结尾增加 hay（apple 会变成 apple-hay）。请注意 UTF-8 编码的细节！
    let s = String::from("hello world");
    println!("{}", to_pig_latin(&s));
    // 使用哈希 map 和 vector，创建一个文本接口来允许用户向公司的部门中增加员工的名字。例如，“Add Sally to Engineering” 或 “Add Amir to Sales”。接着让用户获取一个部门的所有员工的列表，或者公司每个部门的所有员工按照字典序排列的列表。
    manage_employees();
}

use std::io;

fn manage_employees() {
    let mut departments: HashMap<String, Vec<String>> = HashMap::new();

    loop {
        println!(
            "请输入命令 (例如: 'Add 张三 to 技术部' 或 'List 技术部' 或 'ListAll' 或 'exit'):"
        );
        let mut input = String::new();
        io::stdin().read_line(&mut input).expect("读取输入失败");

        let parts: Vec<&str> = input.trim().split_whitespace().collect();

        match parts.as_slice() {
            ["Add", name, "to", department] => {
                // let department = department.to_string();
                // let name = name.to_string();
                departments
                    .entry(department.to_string())
                    .or_default()
                    .push(name.to_string());
                println!("已添加 {} 到 {}", name, department);
            }
            ["List", department] => {
                if let Some(employees) = departments.get(*department) {
                    println!("{} 部门的员工:", department);
                    for employee in employees {
                        println!("- {}", employee);
                    }
                } else {
                    println!("部门 {} 不存在", department);
                }
            }
            ["ListAll"] => {
                let mut sorted_departments: Vec<_> = departments.keys().collect();
                sorted_departments.sort();

                for department in sorted_departments {
                    println!("{} 部门的员工:", department);
                    let mut employees = departments[department].clone();
                    employees.sort();
                    for employee in employees {
                        println!("- {}", employee);
                    }
                }
            }
            ["exit"] => break,
            _ => println!("无效命令，请使用格式: 'Add 姓名 to 部门' 或 'List 部门' 或 'ListAll'"),
        }
    }
}

fn to_pig_latin(s: &str) -> String {
    let vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'];
    let mut result = String::new();

    for word in s.split_whitespace() {
        if let Some(first_char) = word.chars().next() {
            if vowels.contains(&first_char) {
                result.push_str(&format!("{}-hay ", word));
            } else {
                let mut chars = word.chars();
                chars.next();
                let rest: String = chars.collect();
                result.push_str(&format!("{}-{}ay ", rest, first_char));
            }
        }
    }

    result.trim().to_string()
}

fn calculate_stats(numbers: &mut Vec<i32>) -> (f64, i32) {
    // 计算中位数
    numbers.sort();
    let len = numbers.len();
    let median = if len % 2 == 0 {
        (numbers[len / 2 - 1] + numbers[len / 2]) as f64 / 2.0
    } else {
        numbers[len / 2] as f64
    };

    // 计算众数
    let mut counts = HashMap::new();
    for &num in numbers.iter() {
        *counts.entry(num).or_insert(0) += 1;
    }
    let mode = counts
        .into_iter()
        .max_by_key(|&(_, count)| count)
        .map(|(num, _)| num)
        .unwrap_or(0);

    (median, mode)
}
